<template>
  <div class="oe-student-management" v-loading="loading">
    <top-tip v-if="!stepMode && batchTitle" :examTitle="examTitle" :batchTitle="batchTitle" :title="titleList" :goManage="true" :batchid="batchid"></top-tip>
    <div class="oe-manage-content">
      <div class="oe-student-tab">
        <a-radio-group v-if="isHasBK" v-model="typeExam" @change="Changetype" button-style="solid">
          <a-radio-button :value="0">正式卷</a-radio-button>
          <a-radio-button :value="1">补考卷</a-radio-button>
        </a-radio-group>
      </div>
      <div class="oe-manage-content__search">
        <span class="oe-search-label">姓名/学号：</span>
        <span class="oe-search-input" style="width: 12%;">
          <a-input v-model="name" placeholder="请输入姓名/学号" @keyup.13="getStudentList"></a-input>
        </span>
         <span class="oe-search-label">班级：</span>
        <span class="oe-search-input" style="width: 12%;">
          <a-input v-model="className" placeholder="请输入班级名称" @keyup.13="getStudentList"></a-input>
        </span>
        <a-button type="primary" @click.stop="btnsAction(1)">查询</a-button>
        
        <a-button
          type="primary"
          @click.stop="btnsAction(8, '添加补考学生')"
          v-if="operationList.includes('add/edit/del:stu') && paperType == 1"
        >添加补考学生</a-button>

        <a-button
          type="primary"
          @click.stop="btnsAction(9, '删除补考学生')"
          v-if="operationList.includes('add/edit/del:stu') && paperType == 1"
        >删除补考学生</a-button>

        <a-dropdown placement="bottomLeft" v-if="operationList.includes('add/edit/del:stu') && paperType == 0">
          <a-button type="primary">
            学生管理导入
            <a-icon type="down" />
          </a-button>
          <a-menu slot="overlay">
            <a-menu-item>
              <a
                target="_blank"
                rel="noopener noreferrer"
                @click.stop="btnsAction(2, '学生管理导入',1)"
              >按个人导入考生</a>
            </a-menu-item>
            <a-menu-item>
              <a
                target="_blank"
                rel="noopener noreferrer"
                @click.stop="btnsAction(2, '学生管理导入',2)"
              >按班级导入考生</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
        <a-button
          type="primary"
          @click="importExcelQues"
          v-if="operationList.includes('add/edit/del:stu') && paperType == 0"
        >Excel导入</a-button>
        <a-button
          type="primary"
          @click="showAdd"
          v-if="operationList.includes('add/edit/del:stu') && examMode"
        >批量设置考场</a-button>
        <!-- <a-button
          type="primary"
          @click.stop="btnsAction(3, '添加补考')"
          v-if="operationList.includes('add/edit/del:stu')"
        >添加补考</a-button>
        <a-button
          type="primary"
          @click.stop="btnsAction(4, '取消补考')"
          v-if="operationList.includes('add/edit/del:stu')"
        >取消补考</a-button> -->
        <a-button type="primary">
          <a :href="exportUrl">导出成绩</a>
        </a-button>

        <a-button
          type="primary"
          @click.stop="btnsAction(6, '学生管理导入')"
          v-if="operationList.includes('add/edit/del:stu') && examMode"
        >允许线上作答</a-button>
        
        <a-button
          type="primary"
          @click.stop="btnsAction(7, '学生管理导入')"
          v-if="operationList.includes('add/edit/del:stu') && examMode"
        >取消线上作答</a-button>
        
        <a-button
          class="oe-btn-delete"
          @click.stop="btnsAction(5, '批量删除')"
          v-if="operationList.includes('add/edit/del:stu') && paperType == 0"
        >批量删除</a-button>
      </div>
      <div class="oe-manage-content__search">
        作答状态：
        <a-select defaultValue="全部" style="width: 150px" v-model="answerStatus">
          <a-select-option :value="3">全部</a-select-option>
          <a-select-option :value="0">未提交</a-select-option>
          <a-select-option :value="1">已提交(未批阅)</a-select-option>
          <a-select-option :value="2">已提交(已批阅)</a-select-option>
        </a-select>
        <!-- 是否补考：
        <a-select defaultValue="全部" style="width: 150px" v-model="isAginAnswer">
          <a-select-option :value="2">全部</a-select-option>
          <a-select-option :value="0">否</a-select-option>
          <a-select-option :value="1">是</a-select-option>
        </a-select> -->
      </div>
      <div class="oe-manage-content__table">
        <a-table
          :columns=" examMode ? columns2 :columns"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: rowSelection }"
          :dataSource="dataList"
          :pagination="pagination"
          :scroll="{ x: 1600 }"
          @change="onTableChange"
        >
           <span slot="operation" slot-scope="text, record" v-if="(record.State =='已提交未批阅' || record.State =='已提交已批阅') && operationList.includes('add/edit/del:stu')">
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>查看详情</span>
              </template>
              <span
                class="iconfont icon-chakan"
                style="color:#1890ff;cursor: pointer;"
                @click.stop="clickAction(record)"
              ></span>
            </a-tooltip>
          </span>
          <span v-else>--</span>
        </a-table>
      </div>
    </div>
    <a-modal
      :title="设置考场"
      class="oe-studentAdd"
      :visible="add"
      :confirmLoading="confirmLoading"
      @cancel="addCancel"
    >
      <div class="oe-select">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="设置考场" prop="ExamRoomId">
            <a-select
              v-model="form.ExamRoomId"
              showSearch
              :allowClear="true"
              optionFilterProp="children"
              placeholder="请选择考场"
            >
              <a-select-option v-for="item in ExamRoomList" :value="item.Id" :key="item.Id">
                {{
                item.Name
                }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button @click="addSure(0)" type="primary" html-type="submit">确定</a-button>
        <!-- <a-button @click="addSure(1)" type="primary" html-type="submit">补考考试</a-button> -->
        <a-button @click.stop="addCancel">取消</a-button>
      </template>
    </a-modal>
    <a-modal
      v-model="visible"
      title="添加学生"
      width="926px"
      wrapClassName="oe-modal__manage"
      :afterClose="displayCancel"
    >
      <div class="oe-modal-one">
        <a-select
          showSearch
          :value="school"
          placeholder="请选择学校"
          style="width: 200px"
          allowClear
          :defaultActiveFirstOption="false"
          :filterOption="false"
          @search="handleSchoolSearch"
          @change="handleSchoolChange"
          :notFoundContent="spanLoading ? undefined : '无数据'"
        >
          <a-spin v-if="spanLoading" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in schoolList" :key="d.id">{{ d.text }}</a-select-option>
        </a-select>
        <a-select
          showSearch
          :value="factory"
          placeholder="请选择院系"
          style="width: 200px"
          allowClear
          :defaultActiveFirstOption="false"
          :filterOption="false"
          @search="handleFactorySearch"
          @change="handleFactoryChange"
          @focus="getFactoryList('', school)"
          :notFoundContent="factoryLoading ? undefined : '无数据'"
        >
          <a-spin v-if="factoryLoading" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in factoryList" :key="d.id">{{ d.text }}</a-select-option>
        </a-select>
        <a-select
          showSearch
          :value="grade"
          allowClear
          placeholder="请选择年级"
          style="width: 200px"
          :defaultActiveFirstOption="false"
          :filterOption="false"
          @search="handleGradeSearch"
          @change="handleGradeChange"
          @focus="getGradeList('', school)"
          :notFoundContent="gradeLoading ? undefined : '无数据'"
        >
          <a-spin v-if="factoryLoading" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in gradeList" :key="d.id">{{ d.text }}</a-select-option>
        </a-select>
        <a-select
          showSearch
          :value="classes"
          allowClear
          placeholder="请选择班级"
          style="width: 200px"
          :defaultActiveFirstOption="false"
          :filterOption="false"
          @search="handleClassSearch"
          @change="handleClassChange"
          @focus="getClassList('', school)"
          :notFoundContent="classLoading ? undefined : '无数据'"
        >
          <a-spin v-if="classLoading" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in classList" :key="d.id">{{ d.text }}</a-select-option>
        </a-select>
      </div>
      <div class="oe-modal-one">
        <span class="oe-modal-input" v-if="chooseType == 1">
          <a-input placeholder="输入姓名/用户名/学号" v-model="userName" @keyup.13="getImportStudentList">
            <a-icon slot="suffix" type="search" />
          </a-input>
        </span>
        <a-button class="oe-btn-right" type="primary" @click="getImportStudentList">查询</a-button>
      </div>
      <div class="oe-modal-table">
        <a-table
          :columns="chooseType == 1? modalColumns : modalColumnsClass"
          :dataSource="modalList"
          :rowSelection="modalSelection"
          :pagination="modalPagination"
          :scroll="{ y: 470 }"
          @change="onModalChange"
        />
      </div>
      <template slot="footer">
        <a-button type="primary" @click.stop="imporStudentInExam">确认</a-button>
        <a-button class="oe-btn-delete" @click.stop="visible = false">取消</a-button>
      </template>
    </a-modal>

    <a-modal
      v-model="visibleIni"
      title="添加补考学生"
      width="926px"
      wrapClassName="oe-modal__manage"
      :afterClose="displayCancel"
    >
      <div class="oe-modal-one">
        
        <a-select
          showSearch
          :value="classes"
          allowClear
          placeholder="请选择班级"
          style="width: 200px"
          :defaultActiveFirstOption="false"
          :filterOption="false"
          @search="handleClassSearch"
          @change="handleClassChange"
          @focus="getClassList('', school)"
          :notFoundContent="classLoading ? undefined : '无数据'"
        >
          <a-spin v-if="classLoading" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in classList" :key="d.id">{{ d.text }}</a-select-option>
        </a-select>

        <span class="oe-modal-input" v-if="chooseType == 1">
          <a-input placeholder="输入姓名/用户名/学号" v-model="userName" @keyup.13="getInitStudentList">
            <a-icon slot="suffix" type="search" />
          </a-input>
        </span>
        <a-button class="oe-btn-right" type="primary" @click="getInitStudentList">查询</a-button>
      </div>
     
      <div class="oe-modal-table">
        <a-table
          :columns="modalColumnsIni"
          :dataSource="modalList"
          :rowSelection="modalSelection"
          :pagination="modalPagination"
          :scroll="{ y: 470 }"
          @change="onModalChangeIni"
        />
      </div>
      <template slot="footer">
        <a-button type="primary" @click.stop="addReexam(1)">确认</a-button>
        <a-button class="oe-btn-delete" @click.stop="visibleIni = false">取消</a-button>
      </template>
    </a-modal>

    <a-modal
      title="excel导入"
      class="oe-student"
      :visible="importExcel"
      width="40%"
      @cancel="importedCancelExcel"
    >
      <div class="oe-select">
        <span class="oe-manage-select">
          <h2>注意事项：</h2>
          <div>1、导入excel前建议先查看下载模板中的示例，按要求添加导入信息</div>
          <div>2、请按照模板规范顺序导入数据</div>
          <div>3、一次上传的数量请不要大于3000条</div>
          <div>4、导入的学生必须在基础数据中存在</div>
        </span>
      </div>
      <div class="oe-select">
        <a href="/exam/excel/导入考生.xlsx">下载模板</a>
      </div>
      <div>
        <div class="clearfix">
          <a-upload
            :fileList="fileList"
            :remove="handleRemove"
            :beforeUpload="beforeUpload"
            accept=".xlsx"
          >
            <a-button>
              <a-icon type="upload" />选择文件
            </a-button>
          </a-upload>
        </div>
      </div>
      <div class="oe-select-table">
        <a-table
          :columns="errorColumns"
          :dataSource="errorList"
          :pagination="false"
          v-if="errorList.length > 0"
        ></a-table>
      </div>
      <template slot="footer">
        <a-button
          type="primary"
          @click="handleUpload"
          :disabled="fileCount === 0"
          :loading="uploading"
          style="margin-top: 16px"
        >{{ uploading ? '上传中' : '上传' }}</a-button>
        <a-button @click.stop="importedCancelExcel">取消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  name: 'studentManage',
  mixins: [GetOperationList],
  components: {
    topTip
  },
  data() {
    return {
      // 搜索的name
      name: '',
      // 分页配置
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // 分页配置
      modalPagination: {
        pageSizeOptions: ['10', '20', '40', '80', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // title列表
      titleList: [{ text: '批次(考试)管理' }, { text: '考试管理' }, { text: '考生管理', color: '#0177D5' }],
      // 表标题
      columns: [
        {
          title: '序号',
          dataIndex: 'number',
          width: 100,
          key: 'number'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          width: 100,
          key: 'DisplayName',
          sorter: true,
          ellipsis: true
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          width: 150,
          key: 'UserName',
          sorter: true,
          ellipsis: true
        },
        {
          title: '学号',
          dataIndex: 'UserNo',
          width: 150,
          key: 'UserNo',
          sorter: true,
          ellipsis: true
        },
        // {
        //   title: '院系',
        //   dataIndex: 'SubName',
        //   width: 150,
        //   key: 'SubName',
        //   sorter: true,
        //   ellipsis: true
        // },
        // {
        //   title: '专业',
        //   dataIndex: 'MajorName',
        //   width: 150,
        //   key: 'MajorName',
        //   sorter: true,
        //   ellipsis: true
        // },
        // {
        //   title: '年级',
        //   dataIndex: 'GradeName',
        //   width: 150,
        //   key: 'GradeName',
        //   sorter: true,
        //   ellipsis: true
        // },
        {
          title: '班级',
          dataIndex: 'ClassName',
          width: 150,
          key: 'ClassName',
          sorter: true,
          ellipsis: true
        },
        {
          title: '成绩',
          dataIndex: 'GetScore',
          width: 100,
          key: 'GetScore',
          sorter: true,
          ellipsis: true
        },
        {
          title: '批阅状态',
          dataIndex: 'State',
          width: 150,
          key: 'State',
          sorter: true,
          ellipsis: true
        },
        {
          title: '提交时间',
          dataIndex: 'SubmitCreated',
          width: 150,
          key: 'SubmitCreated',
          sorter: true,
          ellipsis: true
        },
        // {
        //   title: '时间',
        //   dataIndex: 'Times',
        //   width: 300,
        //   key: 'Times',
        //   sorter: true
        // },
        {
          title: '口令',
          dataIndex: 'LoginCode',
          width: 150,
          key: 'LoginCode',
          sorter: true,
          ellipsis: true
        }
      ],

      columns2: [
        {
          title: '序号',
          dataIndex: 'number',
          width: 100,
          key: 'number'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          width: 100,
          key: 'DisplayName',
          sorter: true,
          ellipsis: true
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          width: 150,
          key: 'UserName',
          sorter: true,
          ellipsis: true
        },
        {
          title: '学号',
          dataIndex: 'UserNo',
          width: 150,
          key: 'UserNo',
          sorter: true,
          ellipsis: true
        },
        // {
        //   title: '院系',
        //   dataIndex: 'SubName',
        //   width: 150,
        //   key: 'SubName',
        //   sorter: true,
        //   ellipsis: true
        // },
        // {
        //   title: '专业',
        //   dataIndex: 'MajorName',
        //   width: 150,
        //   key: 'MajorName',
        //   sorter: true,
        //   ellipsis: true
        // },
        // {
        //   title: '年级',
        //   dataIndex: 'GradeName',
        //   width: 150,
        //   key: 'GradeName',
        //   sorter: true,
        //   ellipsis: true
        // },
        {
          title: '班级',
          dataIndex: 'ClassName',
          width: 150,
          key: 'ClassName',
          sorter: true,
          ellipsis: true
        },
        {
          title: '成绩',
          dataIndex: 'GetScore',
          width: 100,
          key: 'GetScore',
          sorter: true,
          ellipsis: true
        },
        {
          title: '批阅状态',
          dataIndex: 'State',
          width: 150,
          key: 'State',
          sorter: true,
          ellipsis: true
        },
        {
          title: '提交时间',
          dataIndex: 'SubmitCreated',
          width: 150,
          key: 'SubmitCreated',
          sorter: true,
          ellipsis: true
        },
        {
          title: '是否允许线上作答',
          dataIndex: 'IsAllowOnlineDo',
          width: 200,
          key: 'IsAllowOnlineDo',
          sorter: true,
          ellipsis: true
        },
        {
          title: '时间',
          dataIndex: 'Times',
          width: 300,
          key: 'Times',
          sorter: true
        },
        {
          title: '考场',
          dataIndex: 'ExamRoomName',
          width: 300,
          key: 'ExamRoomName',
          sorter: true,
          ellipsis: true
        },
        {
          title: '座位号',
          dataIndex: 'SeatNumber',
          width: 300,
          key: 'SeatNumber',
          sorter: true,
          ellipsis: true
        },
        // {
        //   title: '口令',
        //   dataIndex: 'LoginCode',
        //   width: 300,
        //   key: 'LoginCode',
        //   sorter: true,
        //   ellipsis: true
        // }
      ],
      // 数据列表
      dataList: [],
      modalColumns: [
        {
          title: '序号',
          dataIndex: 'number',
          width: '8%',
          key: 'number'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          width: '12%',
          key: 'DisplayName',
          sorter: true
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          width: '12%',
          key: 'UserName',
          sorter: true
        },
        {
          title: '学号',
          dataIndex: 'UserNo',
          width: '12%',
          key: 'UserNo',
          sorter: true
        },
        {
          title: '院系',
          dataIndex: 'SubName',
          width: '14%',
          key: 'SubName',
          sorter: true
        },
        {
          title: '专业',
          dataIndex: 'MajorName',
          width: '14%',
          key: 'MajorName',
          sorter: true
        },
        {
          title: '年级',
          dataIndex: 'GradeName',
          width: '14%',
          key: 'GradeName',
          sorter: true
        },
        {
          title: '班级',
          dataIndex: 'ClassName',
          width: '14%',
          key: 'ClassName',
          sorter: true
        }
      ],
      modalColumnsIni: [
        {
          title: '序号',
          dataIndex: 'number',
          width: '8%',
          key: 'number'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          width: '12%',
          key: 'DisplayName',
          sorter: true
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          width: '12%',
          key: 'UserName',
          sorter: true
        },
        {
          title: '学号',
          dataIndex: 'UserNo',
          width: '12%',
          key: 'UserNo',
          sorter: true
        },
        {
          title: '院系',
          dataIndex: 'SubName',
          width: '14%',
          key: 'SubName',
          sorter: true
        },
        {
          title: '专业',
          dataIndex: 'MajorName',
          width: '14%',
          key: 'MajorName',
          sorter: true
        },
        {
          title: '年级',
          dataIndex: 'GradeName',
          width: '14%',
          key: 'GradeName',
          sorter: true
        },
        {
          title: '班级',
          dataIndex: 'ClassName',
          width: '14%',
          key: 'ClassName',
          sorter: true
        },
        {
          title: '成绩',
          dataIndex: 'GetScore',
          width: '14%',
          key: 'GetScore',
          sorter: true
        }
      ],
      modalColumnsClass: [
        {
          title: '序号',
          dataIndex: 'number',
          width: '10%',
          key: 'number'
        },
        {
          title: '班级名称',
          dataIndex: 'Name',
          width: '25%',
          key: 'Name',
          sorter: true
        },
        {
          title: '人数',
          dataIndex: 'StuCount',
          width: '15%'
        },
        {
          title: '班级编码',
          dataIndex: 'Code',
          width: '25%',
          key: 'Code',
          sorter: true
        },
        {
          title: '创建时间',
          dataIndex: 'DateCreated',
          width: '25%',
          key: 'DateCreated',
          sorter: true
        }
      ],
      modalList: [],
      selectedRowKeys: [],
      visible: false,
      visibleIni: false,
      // 搜索学校列表
      schoolList: [],
      // 院系列表
      factoryList: [],
      // 年级列表
      gradeList: [],
      // 班级列表
      classList: [],
      //考场列表
      ExamRoomList: [],
      // 选择的学校
      school: undefined,
      // 选择的院系
      factory: undefined,
      // 班级
      classes: undefined,
      // 年级
      grade: undefined,
      // 输入的用户名和姓名
      userName: '',
      loading: false,
      // 作答状态
      answerStatus: 3,
      // 是否是补考
      isAginAnswer: 2,
      // 选择的数据
      rowSelectList: [],
      defaultkey: [],
      factoryLoading: false,
      gradeLoading: false,
      classLoading: false,
      modalDefaultKey: [],
      modalRowSelect: [],
      uploading: false,
      examMode: false,
      //新增
      add: false,
      form: {
        ExamRoomId: ''
      },
      rules: {
        ExamRoomId: [{ required: true, message: '请选择考场', trigger: 'change' }]
      },
      // 操作的名字
      operationList: [],
      className: '',
      // 操作原始data
      IsOpList: [],
      exportUrl: '',
      importExcel: false,
      fileList: [],
      fileCount: 0,
      errorList: [],
      chooseType: 1,
      errorColumns: [
        {
          title: '序号',
          dataIndex: 'Number',
          align: 'center'
        },
        {
          title: '明细',
          dataIndex: 'Title',
          align: 'center'
        }
      ],
      batchTitle:'',
      examTitle:'',
      typeExam:0, //考试类型
    };
  },
  mounted(){
    this.columns.push({
      title: '操作',
      dataIndex: 'operation',
      width: 100,
      key: 'operation',
      scopedSlots: { customRender: 'operation' }
    });

    this.columns2.push({
      title: '操作',
      dataIndex: 'operation',
      width: 100,
      key: 'operation',
      scopedSlots: { customRender: 'operation' }
    });
    this.getOperation();
  },
  watch: {
    answerStatus(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.getStudentList();
      }
    },
    isAginAnswer(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.getStudentList();
      }
    }
  },
  props: {
    batchid: {
      type: String,
      default: ''
    },
    paperType:{
      type: Number,
      default: 0
    },
    stepMode:{
      type:Boolean,
      default:false
    },
    examid: {
      type: String,
      default: ''
    },
    isHasBK:{
      type:Boolean,
      default:false
    },
  },
  computed: {
    modalSelection() {
      const { modalDefaultKey } = this;
      return {
        selectedRowKeys: modalDefaultKey,
        onChange: this.onModalSelectChange
      };
    },
    examId() {
      return this.examid;
    }
  },
  methods: {
    Changetype({target:{value}}){
      this.paperType = value
      this.dataList = []
      this.addCancel()
      this.getOperation()
    },
    rowSelection(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      var ids = [];
      for (let i = 0; i < selectedRows.length; i++) {
        ids.push(selectedRows[i].Id);
      }
      this.idstudents = ids;
      this.onSelectChange(selectedRowKeys, selectedRowKeys);
    },
    // 判断是否是只读
    getIsWrite(type) {
      type = "add/edit/del:stu";
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    // 重置状态
    displayCancel() {
      this.factory = undefined;
      this.grade = undefined;
      this.classes = undefined;
      // this.school=undefined
      this.userName = '';
      this.modalRowSelect = [];
      this.modalDefaultKey = [];
      this.rowSelectList = [];
    },
    getOperation() {
      this.loading = true;
      this.GetOperationList('examId',this.examid,'studentManage').then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if(item.IsWrite){
              this.operationList.push(item.Name);
              }
            });
            this.IsOpList = rst.list;
          }
          this.getStudentList();
          this.getExamRoomList();
          this.examTitle = rst.examTitle
          this.batchTitle = rst.batchTitle
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    // 获取学校列表
    getSchoolList(val) {
      this.panLoading = true;
      this.$http
        .post('/api/common/localstorage/getExamSchoolList', {
          q: val ? val : '',
          batchId: this.batchid
        })
        .then((rst) => {
          this.panLoading = false;
          if (rst.code == 1) {
            this.schoolList = rst.list;
            this.getImportStudentList('', '', '', 1);
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 获取院系列表
    getFactoryList(search, schoolId) {
      this.factoryLoading = true;
      this.$http
        .post('/api/common/localstorage/getESSubList', {
          q: search,
          schoolId
        })
        .then((rst) => {
          this.factoryLoading = false;
          if (rst.code == 1) {
            this.factoryList = rst.list;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 获取年级列表
    getGradeList(search, schoolId) {
      this.gradeLoading = true;
      this.$http
        .post('/api/common/localstorage/getESGradeList', {
          q: search,
          schoolId,
          subId: this.factory
        })
        .then((rst) => {
          this.gradeLoading = false;
          if (rst.code == 1) {
            this.gradeList = rst.list;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 获取班级列表
    getClassList(search, schoolId) {
      this.classLoading = true;
      this.$http
        .post('/api/common/localstorage/getESClassList', {
          q: search,
          schoolId,
          gradeId: this.grade
        })
        .then((rst) => {
          this.classLoading = false;
          if (rst.code == 1) {
            this.classList = rst.list;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 获取modal选择的
    onModalSelectChange(selectedRowKeys, selectedRow) {
      this.modalDefaultKey = selectedRowKeys;
      this.modalRowSelect = selectedRow;
    },
    // 导入学生
    imporStudentInExam() {
      if (!this.modalDefaultKey.length) {
        if (this.chooseType == 1) {
          this.$message.error(`请先选择要添加的学生`);
          return;
        } else {
          this.$message.error(`请先选择要添加的班级`);
          return;
        }
      }
      let ids = this.modalDefaultKey;
      // this.modalRowSelect.forEach((item) => {
      //   ids.push(item.Id);
      // });
      this.loading = true;
      this.$http
        .post('/api/design/student/saveStu', {
          ids,
          examId: this.examId,
          schoolId: this.school,
          chooseType: this.chooseType
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.$message.success('添加成功');
            this.visible = false;
            this.modalRowSelect = [];
            this.modalDefaultKey = [];
            this.factory = undefined;
            this.grade = undefined;
            this.classes = undefined;
            this.userName = '';
            this.getStudentList();
            this.stepMode && this.$parent.getExamStatus(2)
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 点击table排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getStudentList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 点击table排序
    onModalChangeIni(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getInitStudentList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 点击table排序
    onModalChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getImportStudentList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 获取学生列表
    getStudentList(current, pageSize, sort) {
      this.exportUrl = '/api/design/student/getList?export=1&examId=' + this.examId + '&isRepair=' + this.paperType + "&className="+ this.className+"&key="+this.name + "&sort="+sort;
      this.loading = true;
      this.$http
        .post('/api/design/student/getList', {
          examId: this.examId,
          key: this.name,
          className: this.className,
          state: this.answerStatus === 3 ? '' : this.answerStatus,
          isRepair: this.paperType,
          startScore: '',
          endScore: '',
          sort,
          pageSize: pageSize || 10,
          page: current || 1
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code === 1) {
            this.examMode = rst.examMode;
            this.dataList = [];
            this.defaultkey = [];
            this.pagination.current = rst.pagination.pageIndex;
            this.pagination.pageSize = rst.pagination.pageSize;
            this.pagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                let IsRepair = item.IsRepair ? '是' : '否';
                let State = item.State === 1 ? '已提交未批阅' : item.State === 2 ? '已提交已批阅' : '未提交';
                if (item.State === 1) {
                  if (item.GetScore == 0) {
                    item.GetScore = '--';
                  }
                }
                this.dataList.push({
                  ...item,
                  number: number,
                  key: item.Id,
                  IsRepair,
                  State
                });
              });
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 获取学生导入列表
    getImportStudentList(current, pageSize, sort, type) {
      this.loading = true;
      let apiM = '/api/design/student/getStuList';
      if (this.chooseType == 2) {
        apiM = '/api/design/student/getClassList';
      }
      this.$http
        .post(apiM, {
          chooseType: this.chooseType,
          examId: this.examId,
          schoolId: this.school || '',
          subId: this.factory || '',
          gradeId: this.grade || '',
          classId: this.classes || '',
          key: this.userName || '',
          sort,
          pageSize: pageSize || 10,
          page: current || 1
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code === 1) {
            this.visible = true;
            this.modalList = [];
            this.modalPagination.current = rst.pagination.pageIndex;
            this.modalPagination.pageSize = rst.pagination.pageSize;
            this.modalPagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                let key = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index;
                this.modalList.push({
                  ...item,
                  key: item.Id,
                  number: number
                });
              });
            }
            if (type) {
              let index = this.schoolList.findIndex((item) => {
                return item.id === rst.schoolId;
              });
              if (index > -1) {
                this.school = this.schoolList[index].id;
              }
              this.getImportStudentList();
              // this.getFactoryList('', rst.schoolId);
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },

    // 获取初赛学生列表
    getInitStudentList(current, pageSize, sort, type) {
      this.loading = true;

      this.$http
        .post('/api/design/student/getInitStudentList', {
          examId: this.examId,
          key: this.userName || '',
          classId: this.classes || '',
          sort,
          pageSize: pageSize || 10,
          page: current || 1
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code === 1) {
            this.visibleIni = true;
            this.modalList = [];
            this.modalPagination.current = rst.pagination.pageIndex;
            this.modalPagination.pageSize = rst.pagination.pageSize;
            this.modalPagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                let key = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index;
                this.modalList.push({
                  ...item,
                  key: item.Id,
                  number: number
                });
              });
            }
            if (type) {
              let index = this.schoolList.findIndex((item) => {
                return item.id === rst.schoolId;
              });
              if (index > -1) {
                this.school = this.schoolList[index].id;
              }
              // this.getFactoryList('', rst.schoolId);
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },

    handleMenuClick(e) {
      this.$message.error(e.key);
    },
    // 按钮的事件
    btnsAction(val, type, methords) {
      
      if (val > 1) {
        if (!this.getIsWrite(type)) {
          return;
        }
      }
          
      switch (val) {
        case 1:
          this.getStudentList();
          break;
        case 2:
          this.chooseType = methords;
          this.getSchoolList();
          break;
        case 3:
          this.addReexam(1);
          break;
        case 4:
          this.addReexam(0);
          break;
        case 5:
          this.deleteStudent();
          break;
        case 6:
          this.allowOnlineDo(1);
          break;
        case 7:
          this.allowOnlineDo(0);
          break;
          case 8:
          this.getInitStudentList();
          break;
          case 9:
          this.addReexam(0);
          break;
        default:
          break;
      }
    },
    //获取考场
    getExamRoomList() {
      this.$http
        .post('/api/design/ExamRoom/getExamRoomList', {
          batchId: this.batchid,
          key: this.selectType,
          examId: this.examId
        })
        .then((rst) => {
          this.ExamRoomList = rst.list;
        });
    },
    //新增
    showAdd(value) {
      if (!this.rowSelectList.length) {
        this.$message.error(`请先选择要设置考场的学生！`);
        return;
      }
      this.form = [];
      this.add = true;
    },
    addCancel() {
      this.add = false;
      this.selectedRowKeys = [];
      this.rowSelectList = [];
    },
    addSure(examType) {
      if (!this.rowSelectList.length) {
        this.$message.error(`请先选择要设置考场的学生！`);
        return;
      }
      if (!this.form.ExamRoomId) {
        this.$message.error(`请选择考场！`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.rowSelectList.forEach((item) => {
        ids.push(item);
      });
      this.$http
        .post('/api/design/student/setExamRoom', {
          ids: ids,
          examRoomId: this.form.ExamRoomId,
          batchId: this.batchid,
          examType: examType
        })
        .then((rst) => {
          this.loading = false;
          this.addCancel();
          if (rst.code > 0) {
            this.getStudentList();
            this.$message.success(`设置成功！`);
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 添加补考
    addReexam(val) {

      if(this.modalDefaultKey.length == 0){
        this.modalDefaultKey = this.rowSelectList;
      }

      if (!this.modalDefaultKey.length) {
        this.$message.error(`请先选择要${val ? '补考' : '删除补考'}的学生`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.modalDefaultKey.forEach((item) => {
        ids.push(item);
      });
      this.$http
        .post('/api/design/student/repairStu', {
          examId: this.examId,
          type: val,
          ids
        })
        .then((rst) => {
          this.loading = false;
          this.visibleIni = false;
          this.modalDefaultKey = [];
          this.rowSelectList = [];
          this.addCancel();
          if (rst.code == 1) {
            this.getStudentList();
            this.$message.success(`${val ? '添加' : '删除'}补考成功`);
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 允许线上作答
    allowOnlineDo(val) {
      if (!this.rowSelectList.length) {
        this.$message.error(`请先选择要${val ? '允许线上作答' : '取消线上作答'}的学生`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.rowSelectList.forEach((item) => {
        ids.push(item);
      });
      this.$http
        .post('/api/design/student/allowOnlineDo', {
          examId: this.examId,
          type: val,
          ids
        })
        .then((rst) => {
          this.loading = false;
          this.addCancel();
          if (rst.code == 1) {
            this.getStudentList();
            this.$message.success(`${val ? '添加' : '取消'}线上作答成功`);
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 删除学生列表
    deleteStudent() {
      if (!this.rowSelectList.length) {
        this.$message.error(`请先选择要删除的学生`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.rowSelectList.forEach((item) => {
        ids.push(item);
      });
      this.loading = true;
      this.$http
        .post('/api/design/student/delete', {
          ids,
          examId: this.examId
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.getStudentList();
            this.stepMode && this.$parent.getExamStatus(2)
            this.selectedRowKeys = [];
            this.$message.success('删除成功');
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 查看学生考试详情详情
    clickAction(data) {

      let newPage = this.$router.resolve({
        name: this.$route.name === 'editExamOne' ? 'studentExamDetail4' : 'studentExamDetail',
        params: {
          batchid: this.batchid,
          examid: this.$route.params.examid,
          paperType: this.$route.params.paperType,
          stuid: data.StuId,
          type: data.State == '已提交未批阅' ? 1 : 2
        }
      });
      window.open(newPage.href, '_blank');
    },
    //外层选择的数据
    onSelectChange(selectedRowKeys, selectedRow) {
      this.defaultkey = selectedRowKeys;
      this.rowSelectList = selectedRow;
    },
    // 学校搜索
    handleSchoolSearch(val) {
      this.getSchoolList(val);
    },
    // 改变选择的学校
    handleSchoolChange(val) {
      this.school = val;
    },
    // 院系搜索
    handleFactorySearch(val) {
      this.getFactoryList(val, this.school);
    },
    // 改变选择的院系
    handleFactoryChange(val) {
      this.factory = val;
    },
    // 年级搜索
    handleGradeSearch(val) {
      this.getGradeList(val, this.school);
    },
    // 改变选择的年级
    handleGradeChange(val) {
      this.grade = val;
    },
    // 班级搜索
    handleClassSearch(val) {
      this.getClassList(val, this.school);
    },
    // 改变选择的班级
    handleClassChange(val) {
      this.classes = val;
    },
    importedCancelExcel() {
      this.importExcel = false;
    },
    //点击excel导入
    importExcelQues() {
      if (!this.getIsWrite('学生管理导入')) {
        return;
      }
      this.fileCount = 0;
      this.errorList = [];
      this.fileList = [];
      this.importExcel = true;
    },
    //删除文件
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.errorList = [];
    },
    handleRemoveword(file) {
      const index = this.fileListword.indexOf(file);
      const newFileList = this.fileListword.slice();
      newFileList.splice(index, 1);
      this.fileListword = newFileList;
      this.errorListword = [];
    },
    //选择文件
    beforeUpload(file) {
      this.fileList = [];
      this.fileCount = 1;
      this.fileList = [...this.fileList, file];
      return false;
    },
    //上传
    handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach((file) => {
        formData.append('files[]', file);
        formData.append('examId', this.examId);
      });
      if (this.lock) {
        return;
      }
      this.lock = true;
      this.uploading = true;
      this.$http.post('/api/design/student/importExcelStu', formData).then((res) => {
        this.lock = false;
        this.fileCount = 0;
        this.errorList = [];
        this.uploading = false;
        if (res.code === 100) {
          this.$message.success(res.msg);
          this.getGradeList();
          if (res.list.length) {
            res.list.forEach((item, index) => {
              this.errorList.push({
                Title: item,
                Number: index + 1
              });
            });
          }
        } else if (res.code > 0) {
          this.importExcel = false;
          this.getGradeList();
          this.getStudentList();
          this.stepMode && this.$parent.getExamStatus(2)
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
          // this.errorList = res.list;
          if (res.list.length) {
            res.list.forEach((item, index) => {
              this.errorList.push({
                Title: item,
                Number: index + 1
              });
            });
          }
        }
      });
    }
  }
};
</script>
